package com.mutouren.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;

import com.mutouren.common.exception.ExceptionManager;

public class EncodeUtils {

	public enum EncodeSort {
		MD5("MD5"), 
		SHA_1("SHA-1");

		public final String value;
		private EncodeSort(String value) {
			this.value = value;
		}
	}
	
	public static String getMD5(String value) {
		return getHashCode(EncodeSort.MD5, value);
	}
	
	public static String getHashCode(EncodeSort encodeSort, String value) {
		try {
			MessageDigest md = MessageDigest.getInstance(encodeSort.value);
			md.reset();
			md.update(value.getBytes());
			byte[] hash = md.digest();
			return getHexString(hash);
		} catch (Throwable t) {
			throw ExceptionManager.doUnChecked(t);
		}
	}

	public static String getHexString(byte[] buffer) {
		StringBuilder sb = new StringBuilder(40);
		for (byte b : buffer) {
			sb.append(String.format("%02x", b));
		}
		return sb.toString();
	}
	
	public static byte[] objectBinaryEncode(Object obj) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
	    ObjectOutputStream out = new ObjectOutputStream(outputStream);  
	    out.writeObject(obj);
	    byte[] result = outputStream.toByteArray();
	    out.close();
	    outputStream.close();
	    return result;
	}
	
	public static Object objectBinaryDecode(byte[] buffer) throws IOException, ClassNotFoundException {
		ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);  
	    ObjectInputStream in = new ObjectInputStream(inputStream);  
	    Object result = in.readObject();
	    in.close();
	    inputStream.close();
		return result;
	}
	
}
